﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

/// <summary>
/// 面板基类
/// </summary>
public abstract class BasePanel : MonoBehaviour
{
    //淡入淡出使用组件
    private CanvasGroup canvasGroup;
    //面板是否已经开启
    private bool isShow;
    //渐变动画是否结束
    private bool fadeOver = true;
    //是否开启淡入淡出
    public bool fadeOn = true;
    //淡入淡出速度
    public float fadeSpeed = 10;
    //淡出效果播放完成后执行函数
    private UnityAction hideMeCallBack;

    protected virtual void Awake()
    {
        canvasGroup = GetComponent<CanvasGroup>();
        if (canvasGroup == null) canvasGroup = gameObject.AddComponent<CanvasGroup>();
    }
    private void Start()
    {
        Init();
    }
    protected virtual void Update()
    {
        #region 淡入淡出逻辑
        if (fadeOn)//淡入淡出启用
        {
            if (!fadeOver)//渐变动画播放中
            {
                if (isShow)//显示面板
                {
                    canvasGroup.alpha += fadeSpeed * Time.deltaTime;
                    if (canvasGroup.alpha >= 1)
                    {
                        canvasGroup.alpha = 1;
                        fadeOver = true;//渐变动画结束播放
                    }
                }
                else//隐藏面板
                {
                    canvasGroup.alpha -= fadeSpeed * Time.deltaTime;
                    if (canvasGroup.alpha <= 0)
                    {
                        canvasGroup.alpha = 0;
                        fadeOver = true;//渐变动画结束播放
                        hideMeCallBack?.Invoke();//隐藏自己动画播放完成后执行函数
                    }
                }
            }
        }
        #endregion
    }
    /// <summary>
    /// 初始化
    /// </summary>
    public abstract void Init();

    /// <summary>
    /// 显示面板
    /// </summary>
    public virtual void ShowMe()
    {
        canvasGroup.alpha = fadeOn ? 0: 1;
        isShow = true;
        fadeOver = false;
    }

    /// <summary>
    /// 隐藏面板
    /// </summary>
    /// <param name="callBack">淡出完成执行函数</param>
    public virtual void HideMe(UnityAction callBack = null)
    {
        canvasGroup.alpha = fadeOn ? 1 : 0;
        isShow = false;
        fadeOver = false;
        hideMeCallBack = callBack;
    }
}
